#include"Queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->front = NULL;
	q->rear = NULL;
}

void QueuePush(Queue* q, QDataType data)
{
	assert(q);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->data = data;
	newnode->next = NULL;


	if (q->front == NULL)
	{
		q->front = q->rear = newnode;
	}
	else
	{
		q->rear->next = newnode;
		q->rear = q->rear->next;
	}
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(q->front);
	QNode* ret = q->front;
	q->front = q->front->next;
	free(ret);
	ret = NULL;
	if (q->front == NULL)
		q->rear = NULL;     
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(q->front);
	return q->front->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(q->rear);
	return q->rear->data;
}

int QueueSize(Queue* q)
{
	assert(q);
	int size = 0;
	QNode* cur = q->front;
	while (cur)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

int QueueEmpty(Queue* q)
{
	assert(q);
	return q->front == NULL;
}

void QueueDestroy(Queue* q)
{
	assert(q);
	QNode* cur = q->front;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	q->front = NULL;
	q->rear = NULL;
}